<?php

namespace App\Http\Controllers\Home;

use App\Exceptions\BizException;
use App\Http\Controllers\Controller;
use App\Model\Banner;
use App\Model\Cate;
use App\Model\Goods;
use App\Model\HomeBanner;
use App\Model\HomeItem;
use App\Model\HomeModule;
use App\Model\Sms;
use App\Model\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class HomeController extends Controller
{
    public function newHome(Request $request)
    {
        $params = $request->all();

        // banner
        $banners = HomeBanner::where('status', 1)
            ->orderBy('order_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        // 模块
        $modules = HomeModule::where('status', 1)
            ->orderBy('order_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        // 模块商品
        $moduleItems = HomeItem::with('goods')->orderBy('order_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        return view("home.home.home", [
            'params' => $params,
            'banners' => $banners,
            'modules' => $modules,
            'moduleItems' => $moduleItems,
            'hostName' => $request->getHost(),
        ]);
    }

    // 首页
    public function index(Request $request)
    {
        $params = $request->all();
        $agent = $request->agent;

        // banner
        $banners = Banner::whereIn('agent_id', [0, $agent['id']])
            ->where('status', 1)
            ->orderBy('agent_id', 'asc')
            ->orderBy('order_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        // 分类列表
        $cateList = Cate::where('agent_id', $agent['id'])
            ->where('status', 1)
            ->where('is_home', 1)
            ->orderBy('order_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        // 商品列表
        $model = Goods::where('agent_id', $agent['id'])->where('status', 1)->where('is_home', 1);
        if (empty($params['sort'])) {
            $model->orderBy('order_num', 'desc')->orderBy('id', 'desc');
        } elseif ($params['sort'] == 'hot') {
            $model->orderBy('sale_num', 'desc');
        } elseif ($params['sort'] == 'new') {
            $model->orderBy('id', 'desc');
        }
        $goodsList = $model->get();

        return view("home.{$agent['tpl_id']}.index", [
            'params' => $params,
            'agent' => $agent,
            'banners' => $banners,
            'cateList' => $cateList,
            'goodsList' => $goodsList,
            'agent_id' => $agent['id'],
        ]);
    }

    // 商品列表页
    public function goods(Request $request)
    {
        $pageSize = 20;
        $params = $request->all();
        $agent = $request->agent;

        // 分类列表
        $cateList = Cate::where('agent_id', $agent['id'])
            ->where('status', 1)
            ->orderBy('order_num', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        // 商品列表
        $model = Goods::where('agent_id', $agent['id'])->where('status', 1);
        !empty($params['cate_id']) && $model->where('cate_id', $request->input('cate_id'));
        !empty($params['name']) && $model->where('name', 'like', '%' . $request->input('name') . '%');
        if (empty($params['sort'])) {
            $model->orderBy('order_num', 'desc')->orderBy('id', 'desc');
        } else {
            $params['sort'] == 'price_asc' && $model->orderBy('price', 'asc');
            $params['sort'] == 'price_desc' && $model->orderBy('price', 'desc');
            $params['sort'] == 'sale_asc' && $model->orderBy('sale_num', 'asc');
            $params['sort'] == 'sale_desc' && $model->orderBy('sale_num', 'desc');
        }
        $goodsList = $model->paginate($pageSize);

        if (isset($params['page']) && $params['page'] > 1) {
            return response()->json($goodsList);
        } else {
            return view("home.{$agent['tpl_id']}.goods", [
                'agent' => $agent,
                'cateList' => $cateList,
                'goodsList' => $goodsList,
                'agent_id' => $agent['id'],
            ]);
        }
    }

    // 商品详情
    public function detail(Request $request)
    {
        $id = $request->input('id');
        $agent = $request->agent;

        $goods = Goods::where('status', 1)->where('agent_id', $agent['id'])->where('id', $id)->first();
        if (empty($goods))
            return '<script>alert("该商品已下架")</script>';

        $goods['pic'] = explode(',', $goods['pic']);
        return view("home.{$agent['tpl_id']}.detail", [
            'agent' => $agent,
            'goods' => $goods,
        ]);
    }

    public function login(Request $request)
    {
        $agent = $request->agent;
        if ($request->getMethod() == 'POST') {
            $params = $request->all();
            if (empty($params['username']))
                return response()->json(['status' => 0, 'info' => '用户名不能为空']);
            if (empty($params['password']))
                return response()->json(['status' => 0, 'info' => '密码不能为空']);

            try {
                Users::login($params['username'], $params['password']);
                return response()->json(['status' => 1, 'info' => '登录成功']);
            } catch (\Exception $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            return view("home.{$agent['tpl_id']}.login", [
                'agent' => $agent,
            ]);
        }
    }

    public function logout()
    {
        Auth::logout();
        return redirect('login');
    }

    public function register(Request $request)
    {
        $agent = $request->agent;
        if ($request->getMethod() == 'POST') {
            try {
                $params = $request->all();
                $this->validate($request, [
                    'username' => 'required|unique:users',
                    'code' => 'required',
                    'password' => 'required|same:rePassword',
                ], [
                    'username.required' => '手机号必填',
                    'username.unique' => '该手机号已存在',
                    'code.required' => '验证码必填',
                    'password.required' => '密码必填',
                    'password.same' => '两次密码输入不一致',
                ]);

                if (session('sms_mobile') != $params['username'])
                    throw new BizException('手机号不正确');
                if (session('sms_code') != $params['code'])
                    throw new BizException('验证码不正确');
                if (!preg_match('/^\w{6,15}$/', $params['password']))
                    throw new BizException('密码至少是6位的字母数字组合');

                Users::register($params['username'], $params['password']);
                return response()->json(['status' => 1, 'info' => '注册成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (\Exception $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            return view("home.{$agent['tpl_id']}.register", [
                'agent' => $agent,
            ]);
        }
    }

    // 发送短信验证码
    public function sendSmsCode(Request $request)
    {
        $mobile = $request->input('mobile');
        try {
            if (Users::checkMobileExist($mobile))
                throw new BizException('该手机号已存在');

            $code = Sms::sendCheckCode($mobile);
            session(['sms_code' => $code, 'sms_mobile' => $mobile]);
            return response()->json(['status' => 1, 'info' => '发送成功']);
        } catch (\Exception $e) {
            return response()->json(['status' => 0, 'info' => $e->getMessage()]);
        }
    }

    // 由分类获取商品列表
    public function getGoodsByCate(Request $request)
    {
        $params = $request->all();
        $cate_id = $request->input('cate_id');
        $page = $request->input('page') ?: 1;
        $pageSize = $request->input('pageSize') ?: 20;

        $list = Goods::where('cate_id', $cate_id)
            ->where('status', 1)
            ->where(function ($query) use ($params) {
                !empty($params['name']) && $query->where('name', 'like', "%{$params['name']}%");
            })
            ->skip(($page - 1) * $pageSize)
            ->take($pageSize)
            ->get();
        return response()->json($list);
    }

    public function search(Request $request)
    {
        return view('home.' . $request->agent->tpl_id . '.search');
    }
}